package com.longyi.admin.common;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Random;
import com.longyi.admin.entity.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


public class TokenUtil {
    private static final String SEP = "-";
    private static final byte XOR_KEY = 0x5A;
    private static String username;
    public static String getTokenValue(User user) {
        String raw = user.getId() + SEP + user.getName() + SEP + user.getRole() + SEP + user.getUsername();
        System.out.println(raw);
        byte[] xor = xor(raw.getBytes(StandardCharsets.UTF_8));
        TokenUtil.setUsername(user.getUsername());
        return Base64.getUrlEncoder().withoutPadding().encodeToString(xor);
    }

    //解析token
    public static User TokenValue(String token) {
        byte[] xor = Base64.getUrlDecoder().decode(token);
        byte[] raw = xor(xor);
        String plain = new String(raw, StandardCharsets.UTF_8);
        System.out.println(plain);
        String[] parts = plain.split( SEP, -1);
        User user = new User();
        user.setId(Integer.parseInt(parts[0]));
        user.setName(parts[1]);
        user.setRole(Integer.valueOf(parts[2]));
        user.setUsername(parts[3]);
        System.out.println(user);
        return user;
    }

    private static void setUsername(String username) {
        TokenUtil.username = username;

    }


    /* ------------- 私有工具 ------------- */

    private static byte[] xor(byte[] data) {
        byte[] out = new byte[data.length];
        for (int i = 0; i < data.length; i++) {
            out[i] = (byte) (data[i] ^ XOR_KEY);
        }
        return out;
    }



    //获取用户名
    public static String getUsername() {
        if(TokenUtil.username!=null){
            return username;
        }else{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Token");
            if(token!=null&&!token.isEmpty()){
                User user = TokenValue(token);
                TokenUtil.username=user.getUsername();
                return username;
            }

        }
        return null;
    }
}
